<?php

namespace addons\xilumarket\chatprograms\library;

use app\common\model\xilumarket\ChatSession;
use app\common\model\xilumarket\GroupChatRead;
use app\common\model\xilumarket\Order;
use app\common\model\xilumarket\OrderAddress;
use app\common\model\xilumarket\OrderProduct;
use think\Hook;

class Chat
{
    protected $_error = '';
    /**
     * 当前表情包所有数组数据
     * @return array        数组
     */
    public function chat_memes()
    {
        $data = \app\common\model\xilumarket\ChatEmoji::where('status', 'normal')->order('weigh desc,id desc')->select();
        $arr = [];
        foreach ($data as $key => $value) {
            $arr[] = [
                'name' => $value['name'],
                'image' => cdnurl($value['image'],true),
            ];
        }
        return $arr;
    }
    /**
     * 系统消息的未读个数
     * @return array        数组
     */
    public function init_data($user_id)
    {
        $num = \app\common\model\xilumarket\Chat::where('receive_user_id', $user_id)->where('is_read', 0)->where('see_type', 'in', [0, 1 ,2])->count();
        $sessionIds = ChatSession::where(['send_user_id|receive_user_id|delivery_user_id' => $user_id])->column('id');
        $num += \app\common\model\xilumarket\GroupChat::alias('chat')
            ->join('xl_xilumarket_group_chat_read `read`', '`read`.user_id = '.$user_id.' and `read`.group_chat_id = `chat`.id', 'left')
            ->where('user_id', null)
            ->whereIn('chat.session_id', $sessionIds)
            // ->fetchSql()
            ->count(1);
            // var_dump($sql);
        $data['unread_num'] = $num;
        return $data;
    }
    /**
     * 获取当前通知信息数量 message: {type:getmessagecount,84fec134257974bdcccbf70050e43fa2}
     * @param  [type] $user_id [description]
     * @return [type]          [description]
     */
    public function getmessagecount($user_id,$message_data)
    {
        $returnData = [
            'code' => 1,
            'type' => 'message_count',
            'msg' => '',
            'data' => self::init_data($user_id), //接收数据
        ];
        return $returnData;
    }
    /**
     * 发送消息
     * @param int          $send_user_id  发送人id
     * @param array        $message_data  发送数据{type:say,receive_user_id:xx, content:xx,chat_type:1,session_id:1,see_type:0,84fec134257974bdcccbf70050e43fa2}
     */
    public function say($send_user_id, $message_data, $sessionId = '')
    {
        $returnData = ['code' => 0, 'type' => 'say', 'msg' => '发送失败，请稍后再试', 'data' => null];
        $receive_user_id = $message_data['receive_user_id'] ?? '';
        $product_id = $message_data['product_id'] ?? '';

        // 接收人id和产品id必须同时存在
        if (!$receive_user_id || !$product_id) {
            $returnData['msg'] = '参数错误';
            goto ret;
        }
        if ($receive_user_id == $send_user_id) {
            $returnData['msg'] = '自己不能和自己聊天';
            goto ret;
        }
        // 发送内容和类型必传
        if (empty($message_data['content']) || empty($message_data['chat_type'])) {
            $returnData['msg'] = '参数错误:发送内容和类型必传';
            goto ret;
        }

        if(!$sessionId){
            $sessionId = $message_data['session_id'] ?? '';
        }

        #1.获取会话
        if($sessionId) {
            $session_data = \app\common\model\xilumarket\ChatSession::where('id', $sessionId)->find();
        }else{
            $session_data = \app\common\model\xilumarket\ChatSession::where(function ($query) use ($send_user_id, $receive_user_id) {
            $query->where('send_user_id', $send_user_id)->where('receive_user_id', $receive_user_id)
                ->whereOr(function ($query) use ($send_user_id, $receive_user_id) {
                    $query->where('send_user_id', $receive_user_id)->where('receive_user_id', $send_user_id);
                })->whereOr(function ($query) use ($send_user_id, $receive_user_id) {
                    $query->where('delivery_user_id', $send_user_id)->where('receive_user_id', $receive_user_id);
                });
            })
            ->where('product_id',$product_id)
            ->find();
        }
        //3为单独初始化进程-不添加聊天记录
        if ($message_data['chat_type'] == 3){
            $product = \app\common\model\xilumarket\Product::field("id,name,thumb_image,salesprice,line_price,want_num")->where('id',$message_data['content'])->find();
            if (!$product) {
                $returnData['msg'] = '参数错误:无法查询到该商品信息';
                goto ret;
            }
            $message_data['content'] = [
                'id' => $product['id'],
                'name' => $product['name'],
                'image' => $product['thumb_image_text'],
                'salesprice' => $product['salesprice'],
                'line_price' => $product['line_price'],
                'want_num' => $product['want_num']
            ];
            $message_data['content'] = json_encode($message_data['content']);
        }
        //可见状态:0=正常,1=自动打招呼(发送人不可见),2=发送人被拉黑(接收人不可见),3=接收人被拉黑(发送人不可见),4=相互拉黑(两方都不可见)
        $see_type = $message_data['see_type'] ?? 0;
        // 如果没有会话，直接创建新的会话
        if (!$session_data) {
            $res = \app\common\model\xilumarket\ChatSession::create([
                'send_user_id' => $send_user_id,
                'receive_user_id' => $receive_user_id,
                'product_id' => $message_data['product_id'],
                'see_type' => $see_type,
            ]);
            if (!$res) {
                goto ret;
            }
            $session_data = \app\common\model\xilumarket\ChatSession::get($res->id);
        }
        $returnData['data']['session_id'] = $session_data['id'];
        if($message_data['chat_type'] == 3){
            //想要数量增加
            \app\common\model\xilumarket\ProductWant::add($send_user_id,$product_id);
            $returnData['code'] = '2';
            $returnData['msg'] = '商品进程已存在';
            goto ret;
        }
        
        $hookParams = [$message_data, $send_user_id, $session_data];
        list($retData) = Hook::listen('create_chat_info', $hookParams);
        $returnData = array_merge($returnData, $retData);
        $session_data->updatetime = time();
        $session_data->allowField(['updatetime'])->save();
        ret:
        return $returnData;
    }
    /**
     * 会话列表
     * @param int          $user_id  用户id
     * @param array        $message_data  发送数据{session_time:0,session_id:0}
     */
    public function sessionlist($user_id, $message_data)
    {
        $returnData = [
            'code' => 0,
            'type' => 'session_list',
            'msg' => '参数错误',
            'data' => '', //接收数据
        ];
        // // 判断是否传页数过来
        if ((!isset($message_data['pagesize'])) || (!isset($message_data['page']))) {
            goto ret;
        }
        $where = [];
        $chatsessionModel = new \app\common\model\xilumarket\ChatSession;
        $chatmsgModel = new \app\common\model\xilumarket\Chat;
        $groupChatmsgModel = new \app\common\model\xilumarket\GroupChat();
        // 未读个数 聊天记录的可见状态:0=正常,1=发送人删除记录(发送人不可见),2=接收人删除记录(接收人不可见),3=发送人撤回消息(双方都不可见),4=双方都删除记录

        // 会话的可见状态:0=正常,1=发送人被拉黑(接收人不可见),2=接收人被拉黑(发送人不可见),4=相互拉黑(两方都不可见)
        $data = $chatsessionModel
            ->field(['id', 'send_user_id', 'receive_user_id', 'product_id', 'see_type','updatetime','delivery_user_id', 'deletetime'])
            ->with([
                'senduser' => function ($que) {
                    $que->withField('id,nickname,avatar,gender');
                }, 'receiveuser' => function ($que) {
                    $que->withField('id,nickname,avatar,gender');
                },'deliveryuser' => function ($que) {
                    $que->withField('id,nickname,avatar,gender');
                }, 'newmsg','newgroupmsg','product'=>function($que){
                    $que->withField("id,product_type,name,user_id,thumb_image,salesprice,line_price,want_num");
            }])
            ->where(function ($query) use ($user_id, $where) {
                $query->where('send_user_id', $user_id)->where('see_type', 'in', [0, 1])->where('senddeletetime', null)->where($where);
            })->whereOr(function ($query) use ($user_id, $where) {
                $query->where('receive_user_id', $user_id)->where('see_type', 'in', [0, 2])->where('receivedeletetime', null)->where($where);
            })->whereOr(function ($query) use ($user_id) {
                $query->where('delivery_user_id', $user_id);
            })->order('chat_session.updatetime desc,chat_session.id desc')
            ->paginate($message_data['pagesize'], false, ['page' => $message_data['page']])
            ->each(function ($row) use($chatmsgModel, $groupChatmsgModel,$user_id){
                if($row->delivery_user_id) {
                    $row->unread_num = $groupChatmsgModel->alias('chat')
                        ->where('chat.session_id',$row->id)
                        ->join('xl_xilumarket_group_chat_read `read`', '`read`.user_id = '.$user_id.' and `read`.group_chat_id = `chat`.id', 'left')
                        ->where('user_id', null)
                        ->count(1);
                }else{
                    $row->unread_num = $chatmsgModel->where('session_id',$row->id)->where('receive_user_id',$user_id)->where('is_read',0)->where('see_type', 'in', [0, 1])->count(1);
                }
            });
        $returnData['code'] = 1;
        $returnData['msg'] = '';
        $returnData['data'] = $data;
        ret:
        return $returnData;
    }
    /**
     * 聊天记录
     * @param int          $user_id  用户id
     * @param array        $message_data  发送数据{page:1,product_id:1,receive_user_id:0}
     */
    public function msglist($user_id, $message_data)
    {
        $returnData = [
            'code' => 0,
            'type' => 'msg_list',
            'msg' => '参数错误',
            'data' => [
                'current_page' => 1,
                'data' => [],
                'last_page' => 0,
                'total' => 0,
            ], //接收数据
            'receiveuser' => null,
        ];
        $receive_user_id = $message_data['receive_user_id'] ?? '';
        $product_id = $message_data['product_id'] ?? '';
        $page = $message_data['page'] ?? '1';
        $sessionId = $message_data['session_id'] ?? 0;
        // 接收人id和会话id必须有一个
        if (!$receive_user_id || !$product_id) {
            goto ret;
        }

        // 判断是否有会话id
        
        #1.获取会话
        if($sessionId) {
            $session_data = \app\common\model\xilumarket\ChatSession::where('id', $sessionId)->find();
        }else{
            $session_data = \app\common\model\xilumarket\ChatSession::with(['product'])->
            where(function ($query) use ($user_id, $receive_user_id) {
                $query->where(function ($query) use($user_id,$receive_user_id){
                    $query->where('send_user_id', $user_id)->where('receive_user_id', $receive_user_id);
                })->whereOr(function ($query) use ($user_id, $receive_user_id) {
                    $query->where('send_user_id', $receive_user_id)->where('receive_user_id', $user_id);
                });
            })
            ->where('product_id',$product_id)
            ->find();
        }
        // 如果没有会话，直接返回空数组
        if (!$session_data) {
            $returnData['code'] = 1;
            $returnData['msg'] = '';
            // 获取接收人数据
            $returnData['receiveuser'] = \app\common\model\User::field('id,nickname,avatar,gender')->find($receive_user_id);
            goto ret;
        }

        $session_id = $session_data['id'];
        if($session_data['delivery_user_id']){
            $data = \app\common\model\xilumarket\GroupChat::field(['id', 'session_id', 'send_user_id', 'content', 'chat_type', 'createtime'])
                ->where('session_id',$session_id)
                ->with(['session', 'senduser' => function ($que) {
                    $que->withField('id,nickname,avatar,gender');
                }])
                ->order('createtime desc')
                ->paginate(20, false, ['page' => $page]);
            $order = OrderProduct::alias('product', 'product.order_id')
                ->join('xl_xilumarket_order order', 'order.id=product.order_id')
                ->field(['product.order_id'])
                ->where(['product.product_id' => $session_data['product_id'], 'order.pay_status' => 2])
                // ->fetchSql()
                ->find();
                // var_dump($order);
            $address = OrderAddress::where(['order_id' => $order['order_id']])->find();
            $returnData['addresses']['seller'] = $session_data['product']['address'];
            $returnData['addresses']['buyer'] = $address['address_detail'].$address['address'];
        }else{
            // 可见状态:0=正常,1=发送人删除记录(发送人暂不可见),2=接收人删除记录(接收人不可见),3=发送人撤回消息(双方都不可见),4=双方都删除记录
            $data = \app\common\model\xilumarket\Chat::
                field(['id', 'session_id', 'send_user_id', 'receive_user_id', 'content', 'chat_type', 'see_type', 'createtime',])
                ->with(['senduser' => function ($que) {
                    $que->withField('id,nickname,avatar,gender');
                }, 'receiveuser' => function ($que) {
                    $que->withField('id,nickname,avatar,gender');
                }])
                ->where('session_id',$session_id)
                ->where(function ($query) use ($user_id) {
                    $query->where(function ($query) use($user_id){
                        $query->where('send_user_id', $user_id)->where('see_type', 'in', [0, 2]);
                    })
                        ->whereOr(function ($query) use ($user_id) {
                        $query->where('receive_user_id', $user_id)->where('see_type', 'in', [0, 1]);
                    });
                })
                ->order('chat.id desc')->paginate(10, false, ['page' => $page]);
        }


        $returnData['code'] = 1;
        $returnData['msg'] = '';
        $returnData['data'] = $data;
        // 获取接收人数据
        $returnData['receiveuser'] = \app\common\model\User::field('id,nickname,avatar,gender')->find($receive_user_id);
        ret:
        return $returnData;
    }
    // product_id: "21"
    // receive_user_id: 3
    // session_id: "3"
    // type: "setread"

    /**
     * 设为已读
     * @param int          $user_id  用户id
     * @param array        $message_data  发送数据{session_id:1,receive_user_id:0}
     */
    public function setread($user_id, $message_data){
        $returnData = ['code' => 0, 'type' => 'set_read', 'msg' => '参数错误', 'data' => null];
        // 接收人id和会话id必须有一个
        $receive_user_id = $message_data['receive_user_id'] ?? '';
        $product_id = $message_data['product_id'] ?? '';
        if (!$receive_user_id || !$product_id) {
            goto ret;
        }
        $session_id = $message_data['session_id'] ?? 0;
        // 查询会话
        if($session_id){
            $session_data = \app\common\model\xilumarket\ChatSession::find($session_id);
        }else{
            $session_data = \app\common\model\xilumarket\ChatSession::where(function ($query) use ($user_id, $receive_user_id) {
                $query->where(function ($query) use($user_id,$receive_user_id){
                    $query->where('send_user_id', $user_id)->where('receive_user_id', $receive_user_id);
                })->whereOr(function ($query) use ($user_id, $receive_user_id) {
                    $query->where('send_user_id', $receive_user_id)->where('receive_user_id', $user_id);
                });
            })
            ->where('product_id',$product_id)
            ->find();
        }
        // 如果没有会话，直接返回空数组
        if (!$session_data) {
            goto ret;
        }

        $session_id = $session_data['id'];

        if($session_data['delivery_user_id']){
            $readids = \app\common\model\xilumarket\GroupChatRead::where('session_id', $session_id)
                ->where('user_id', $user_id)->column('group_chat_id');
            $chats = \app\common\model\xilumarket\GroupChat::where(['session_id' => $session_id])
                ->whereNotIn('id', $readids)->select();
            $res = [];
            foreach($chats as $chat) {
                $res[] = [
                    'user_id'   => $user_id,
                    'session_id'    => $session_id,
                    'group_chat_id' => $chat['id'],
                ];
            }
            $model = new \app\common\model\xilumarket\GroupChatRead();
            $model->saveAll($res);
        }else{
            \app\common\model\xilumarket\Chat::where('session_id', $session_id)->where('receive_user_id', $user_id)->where('is_read', 0)->update(['is_read' => 1]);
        }

        $returnData['code'] = 1;
        $returnData['msg'] = '';
        ret:
        return $returnData;
    }
    /**
     * 删除会话
     * @param int          $user_id  用户id
     * @param array        $message_data  发送数据{session_id:1}
     */
    public function delsession($user_id, $message_data)
    {
        $returnData = [
            'code' => 0,
            'type' => 'del_session',
            'msg' => '参数错误',
            'data' => [], //接收数据
        ];
        // 判断是否传会话id过来
        if ((!isset($message_data['session_id']) || !$message_data['session_id'])) {
            goto ret;
        }
        // 判断是否存在该会话
        $session_id = $message_data['session_id'];
        $session_data = \app\common\model\xilumarket\ChatSession::get($message_data['session_id']);
        if (!$session_data || ($session_data['send_user_id'] != $user_id && $session_data['receive_user_id'] != $user_id)) {
            goto ret;
        }
        if ($session_data['send_user_id'] == $user_id) {
            $session_data->save(['senddeletetime' => time()]);
        } else {
            $session_data->save(['receivedeletetime' => time()]);
        }
        $returnData['code'] = 1;
        $returnData['msg'] = '';
        $returnData['data'] = ['session_id' => $session_id];
        ret:
        return $returnData;
    }

    /**
     * 自动回复
     *
     * @param int $user_id
     * @param array $message_data
     * @return mixed
     */
    public function autoreplay($user_id, $message_data) {
        $returnData = [
            'code' => 0,
            'type' => 'autoreplay',
            'msg' => '参数错误',
            'data' => [], //接收数据
        ];
        if(!isset($message_data['session_id'])){
            return $returnData;
        }
        $session_data = \app\common\model\xilumarket\ChatSession::get($message_data['session_id']);
        if (!$session_data || ($session_data['send_user_id'] != $user_id && $session_data['receive_user_id'] != $user_id)) {
            return [];
        }
        $hookParams = [$message_data, $user_id, $session_data];
        list($ret) = Hook::listen('autoreplay', $hookParams);
        $ret = array_merge($returnData, $ret);
        return $ret;
    }
}
